<template>
  <div>
    <h1 style="text-align: center; margin: 100px auto; font-size: 50px;font-style: italic; color: #010112  " >宜春学院班费管理系统</h1>
    <div style="width: 400px; height: 300px ;background: #fff; margin: 60px auto; padding: 20px 50px">
      <h1 style="text-align: center; margin: 30px auto;" >用户登录</h1>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password:'',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://127.0.0.1:8080/user/login';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);
          this.axios.post(url,formData).then(response=>{
            let responseBody = response.data;
            if (responseBody.state == 20000){
              this.$message({
                message:'登录成功',
                type:"success",
              })
              let jwt = responseBody.data;
              console.log("登录成功,响应jwt:" + jwt);
              localStorage.setItem('jwt',jwt);
              localStorage.setItem('username',this.ruleForm.username);
              console.log('已经将jwt保存到localStorage')
              console.log('已经将username保存到localStorage')
              location.href = "/";
            }else {
              console.log(responseBody.message);
              this.$message.error(responseBody.message);
            }
          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
body {
  background: #B3C0D1;
  /*background-image:url("https://img2.baidu.com/it/u=1119585672,1899188854&fm=253&fmt=auto&app=138&f=JPEG?w=658&h=287");*/
}
</style>